const article = require("../mongoose/article");
const { articleAddVerify } = require("../verifyParams/article");

exports.articleAll = async (ctx) => {
  try {
    let res = await article.find();
    if (!res.length) throw new Error("服务器错误 查询失败");
    ctx.body = {
      status: 200,
      msg: "获取数据成功",
      data: res,
    };
  } catch {
    ctx.body = {
      status: 100,
      msg: "获取数据失败",
      data: res,
    };
  }
};

exports.articleAdd = async (ctx) => {
  ctx.verifyParams(articleAddVerify);
  console.log(ctx.request.body);
  try {
    let res = await article.create(ctx.request.body);
    console.log(res);
    // if (!res.length) throw new Error("服务器错误 添加失败");
    ctx.body = {
      status: 200,
      msg: "获取数据成功",
      data: res,
    };
  } catch {
    ctx.body = {
      status: 100,
      msg: "获取数据失败",
      data: res,
    };
  }
};

exports.articleDel = async (ctx) => {
  try {
    let res = await article.findByIdAndRemove({ _id: ctx.params.id });
    console.log(res);
    ctx.body = {
      status: 200,
      msg: "删除数据成功",
      data: res,
    };
  } catch {
    ctx.body = {
      status: 100,
      msg: "删除数据失败",
      data: res,
    };
  }
};

exports.articleUpdate = async (ctx) => {
  try {
    let res = await article.findByIdAndUpdate(
      { _id: ctx.request.body.id },
      { author: ctx.request.body.author }
    );
    console.log(res);
    ctx.body = {
      status: 200,
      msg: "更新数据成功",
      data: res,
    };
  } catch {
    ctx.body = {
      status: 100,
      msg: "更新数据失败",
      data: res,
    };
  }
};
